<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增销售订单')" />
    <th:block th:include="include :: datetimepicker-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-order-add">
            <div class="form-group">    
                <label class="col-sm-3 control-label">订单号：</label>
                <div class="col-sm-8">
                    <div class="input-group">
                        <input id="orderCode" name="orderCode" class="form-control" type="text" th:value="${saleOrderNo}" readonly>
                        <span class="input-group-addon"><a href="javascript:refreshOrder()"><i class="fa fa-refresh"></i>刷新单号</a></span>
                    </div>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">供方：</label>
                <div class="col-sm-8">
                    <input name="providerName" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">客户：</label>
                <div class="col-sm-8">
                    <div class="input-group">
                        <input id="customerId" name="customerId" type="hidden" >
                        <input id="customerName" name="customerName" class="form-control" type="text" onclick="selectCustomer()" readonly required>
                        <span class="input-group-addon"><i class="fa fa-search"></i></span>
                    </div>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">业务责任人：</label>
                <div class="col-sm-8">
                    <input name="businessManager" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">订单日期：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <input name="orderDate" class="form-control" placeholder="yyyy-MM-dd" type="text">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">销售总量：</label>
                <div class="col-sm-8">
                    <input id="allNums" name="allNums" class="form-control" type="number" step="0.01">
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">销售总价：</label>
                <div class="col-sm-8">
                    <input id="amounts" name="amounts" class="form-control" type="number" step="0.01">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">备注：</label>
                <div class="col-sm-8">
                    <textarea name="remark" class="form-control" maxlength="200"></textarea>
                </div>
            </div>

            <div class="row">
                <div class="col-sm-12">
                    <button type="button" class="btn btn-white btn-sm" onclick="addColumn()"><i class="fa fa-plus"> 增加</i></button>
                    <button type="button" class="btn btn-white btn-sm" onclick="sub.delRow()"><i class="fa fa-minus"> 删除</i></button>
                    <div class="col-sm-12 select-table table-striped">
                        <table id="bootstrap-table"></table>
                    </div>
                </div>
            </div>
        </form>

        <div class="row">
            <div class="col-sm-offset-5 col-sm-10">
                <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>保 存</button>&nbsp;
                <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭 </button>
            </div>
        </div>
    </div>

    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <script th:inline="javascript">
        let prefix = ctx + "order/saleorder"
        let goodsUnitDatas = [[${@dict.getType('product_unit')}]];//商品单位
        $("#form-order-add").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                $.operate.saveTab(prefix + "/add", $('#form-order-add').serialize());
            }
        }

        function  refreshOrder() {
            var config = {
                url: prefix + "/getOrderNo",
                type: "GET",
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍后...");
                },
                success: function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $("#orderCode").val(result.data)
                    } else {
                        $.modal.alertError(result.msg);
                    }
                    $.modal.closeLoading();
                }

            };
            $.ajax(config);
        }

        $("input[name='orderDate']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $(function() {
            // 初始化数据, 可以由后台传过来
            let data = [];
            let options = {
                data: data,
                pagination: false,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",
                uniqueId: "index",
                // queryParams: queryParams,
                // onLoadSuccess: onLoadSuccess,//所有数据被加载成功触发
                columns: [{
                    checkbox: true
                },
                    {
                        field: 'index',
                        align: 'center',
                        title: "序号",
                        formatter: function (value, row, index) {
                            var columnIndex = $.common.sprintf("<input type='hidden' name='index' value='%s'>", $.table.serialNumber(index));
                            return columnIndex + $.table.serialNumber(index);
                        }
                    },
                    {
                        field: 'id',
                        align: 'center',
                        title: 'id',
                        visible: false
                    },
                    {
                        field: 'goodsName',
                        align: 'center',
                        title: '商品名称',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' name='items[%s].goodsName' value='%s' readonly>", index, value);
                            var goodsId = $.common.sprintf("<input type='hidden' name='items[%s].goodsId' value='%s'>", index, row.goodsId);//商品id 隐藏域
                            var goodsCode = $.common.sprintf("<input type='hidden' name='items[%s].goodsCode' value='%s'>", index, row.goodsCode);//商品code 隐藏域
                            return html+goodsId+goodsCode;
                        },
                        events: onclickEvent
                    },
                    {
                        field: 'goodsUnitDesc',
                        align: 'center',
                        title: '单位',
                        formatter: function (value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' name='items[%s].goodsUnitDesc' value='%s' readonly>", index, value);
                            var goodsUnit = $.common.sprintf("<input type='hidden' name='items[%s].goodsUnit' value='%s'>", index, row.goodsUnit);//商品unit
                            return html+goodsUnit;
                        }
                    },
                    {
                        field: 'saleNumber',
                        align: 'center',
                        title: '数量',
                        formatter: function(value, row, index) {
                            var html = '<input class="form-control" type="number" name="items['+index+'].saleNumber" value="'+value+'" maxlength="6" oninput="reloadRowNumberDatas(' + index + ',this,'+row.price+')" required>';
                            return html;
                        }
                    },
                    {
                        field: 'price',
                        align: 'center',
                        title: '单价',
                        formatter: function(value, row, index) {
                            var html = '<input class="form-control" type="text" name="items['+index+'].price" value="'+value+'" maxlength="8" oninput="reloadRowPriceDatas('+index+','+row.saleNumber+',this)" required>';
                            return html;
                        }
                    },
                    {
                        field: 'amount',
                        align: 'center',
                        title: '总价',
                        formatter: function(value, row, index) {
                            var html = '<input class="form-control" type="text" name="items['+index+'].amount" value="'+value+'" maxlength="14"  readonly>';
                            return html;
                        }
                    },
                    {
                        field: 'remark',
                        align: 'center',
                        title: '要求',
                        formatter: function (value, row, index) {
                            var html = '<textarea class="form-control"  name="items[' + index + '].remark" maxlength="200">' + value + '</textarea>';
                            return html;
                        }
                    }
                ]
            };
            $.table.init(options);
        });

        //新增table行
        function addColumn() {
            let row = {
                id: "",
                goodsId: "",
                goodsName: "",
                goodsUnit: "",
                goodsUnitDesc:"",
                saleNumber: 1,
                price: 0,
                amount: 0,
                remark: ""
            }
            sub.addRow(row);
        }

        /* 选择客户 */
        let customerPrefix = ctx + "basic/customer"
        function selectCustomer() {
            let url = customerPrefix + '/selectCustomer';
            let options = {
                title: '选择客户',
                url: url,
                callBack: doSubmitCustomer
            };
            $.modal.openOptions(options);
        }

        function doSubmitCustomer(index, layero){
            var iframeWin = layero.find("iframe")[0].contentWindow.$.table;
            var rows = iframeWin.selectFirstColumns();//调用子页面的方法 获取ID
            if (rows.length == 0) {
                $.modal.alertWarning("请至少选择一条记录");
                return;
            }
            $('#customerId').val(rows.join())
            var customerName=iframeWin.selectColumns("customerName").join();//调用子页面的方法 获取ID
            $('#customerName').val(customerName)

            $.modal.close(index);
        }

        /* 选择商品 */
        let goodsPrefix = ctx + "basic/goods"
        function  selectShopGoods() {// index:所在行的索引
            let url = goodsPrefix + '/selectGoods';
            let options = {
                title: '选择商品',
                url: url,
                callBack: doSubmitGoods
            };
            $.modal.openOptions(options);
        }
        let orderSeedId;//子表ID
        function doSubmitGoods(index, layero){
            var iframeWin = layero.find("iframe")[0].contentWindow.$.table;
            var rows = iframeWin.selectFirstColumns();//调用子页面的方法 获取ID
            if (rows.length == 0) {
                $.modal.alertWarning("请至少选择一条记录");
                return;
            }

            var goodsId=iframeWin.selectColumns("id").join();//调用子页面的方法 获取ID
            var goodsCode=iframeWin.selectColumns("goodsCode").join();//调用子页面的方法 获取ID
            var goodsName=iframeWin.selectColumns("goodsName").join();//调用子页面的方法 获取ID
            var goodsUnit=iframeWin.selectColumns("goodsUnit").join();//调用子页面的方法 获取ID
            var planNumber=iframeWin.selectColumns("planNumber").join();//调用子页面的方法 获取ID
            var goodsUnitDesc = "";//单位描述
            $.each(goodsUnitDatas,function(index,obj){  //index:索引obj:循环的每个元素
                if(obj.dictValue == goodsUnit){
                    goodsUnitDesc= obj.dictLabel;
                }
            });
            var data = $("#" + table.options.id).bootstrapTable('getData');
            var flag=0;
            $.each(data,function(index,obj) {  //index:索引obj:循环的每个元素
                if(obj.goodsId ==  goodsId){
                    flag=1;
                    return false; //跳出循环
                }
            });
            if(flag == 1){$.modal.alertWarning("商品已在清单中!"); return;}

            $.modal.close(index);

            var _data = new Object();//某行数据
            _data.goodsId = goodsId;
            _data.goodsCode = goodsCode;
            _data.goodsName = goodsName;
            _data.goodsUnit = goodsUnit;
            _data.goodsUnitDesc = goodsUnitDesc;
            _data.saleNumber = planNumber;
            $("#" + table.options.id).bootstrapTable("updateRow",{index : orderSeedId,row : _data});

        }

        /**
         * 选中商品事件
         * */
        window.onclickEvent = {
            'click .form-control': function (e, value, row, index) {
                orderSeedId = index
                selectShopGoods();
            }
        };

        /**
         * 修改数量计算金额
         * */
        function reloadRowNumberDatas(index, obj, price) {
            if ($.common.isNotEmpty(index) && $.common.isNotEmpty(price)) {
                var number = $(obj).val();
                if ($.common.isEmpty(number) || !(/(^[1-9]\d*$)/.test(number))) {//正整数
                    $.modal.alertWarning("不能为空或输入的不是正整数");
                    return;
                }
                updateCell(index, number, price);//修改值
            }
        }

        /**
         * 修改单价计算金额
         * */
        function reloadRowPriceDatas(index, number, obj) {
            if ($.common.isNotEmpty(index) && $.common.isNotEmpty(number)) {
                var price = $(obj).val();
                var regu = /^\d+(\.{0,1}\d{1,2})?$/;//非负浮点数（正浮点数 + 0）
                if ($.common.isEmpty(price) || !regu.test(price)) {
                    $.modal.alertWarning("不能为空或输入的不是非负浮点数(只能保留2位)");
                    return;
                }
                updateCell(index, number, price);//修改值
            }
        }

        //更新指定的列数据
        function updateCell(index, planNumberVal, taxUnitPriceVal) {//更新表格数据
            var _data = new Object();//某行数据
            _data.saleNumber = planNumberVal;
            _data.price = taxUnitPriceVal;
            _data.amount = numMulti(planNumberVal, taxUnitPriceVal);
            $("#" + table.options.id).bootstrapTable("updateRow", {index: index, row: _data});
            //总计
            calculate()

        }

        /**
         * 计算合计商品各项值之和
         */
        function calculate() {
            var data = $("#" + table.options.id).bootstrapTable('getData');//查询表格所有数据
            console.info(JSON.stringify(data))
            var totalAmount = 0;
            var totalNumber = 0;
            $.each(data, function (index, obj) {
                if($.common.isNotEmpty(obj.amount)) {
                    totalAmount = numAdd(totalAmount, obj.amount);
                }
                if($.common.isNotEmpty(obj.saleNumber)) {
                    totalNumber = numAdd(totalNumber, obj.saleNumber);
                }
            });
            $('#amounts').val(totalAmount);
            $('#allNums').val(totalNumber);
        }

    </script>
</body>
</html>